package org.dreamwork.sso.saml2.util;

import org.opensaml.xml.XMLObject;
import org.opensaml.xml.XMLObjectBuilder;
import org.opensaml.xml.XMLObjectBuilderFactory;

import javax.xml.namespace.QName;
import java.lang.reflect.Field;

/**
 * Created with IntelliJ IDEA.
 * User: seth.yang
 * Date: 13-8-14
 * Time: 下午1:54
 */
public class SamlHelper {
    @SuppressWarnings ("unchecked")
    public static<T extends XMLObject> T createObject (Class<T> type, XMLObjectBuilderFactory factory, String uri, String prefix) throws NoSuchFieldException, IllegalAccessException {
        Field field = type.getField ("DEFAULT_ELEMENT_NAME");
        QName qName = (QName) field.get (null);

        field = type.getField ("TYPE_NAME");
        QName typeName = (QName) field.get (null);

        field = type.getField ("DEFAULT_ELEMENT_LOCAL_NAME");
        String localName = (String) field.get (null);

        XMLObjectBuilder<T> builder = factory.getBuilder (qName);
        return builder.buildObject (uri, localName, prefix, typeName);
    }

    @SuppressWarnings ("unchecked")
    public static<T extends XMLObject> T createObject (Class<T> type, XMLObjectBuilderFactory factory) {
        try {
            Field field = type.getField ("DEFAULT_ELEMENT_NAME");
            QName qName = (QName) field.get (null);

            field = type.getField ("TYPE_NAME");
            QName typeName = (QName) field.get (null);

            XMLObjectBuilder<T> builder = factory.getBuilder (qName);
            return builder.buildObject (qName, typeName);
        } catch (Exception ex) {
            throw new RuntimeException (ex);
        }
    }
}
